package com.zzsz.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.zzsz.annotation.ZzszRecordStockLog;
import com.zzsz.domain.ProductsCategoriesInventoryVO;
import com.zzsz.domain.ZzszAddProductsDTO;
import com.zzsz.enums.OperationType;
import com.zzsz.mapper.InventoryMapper;
import com.zzsz.service.InventoryService;
import com.zzsz.domain.ZzszProductCategories;
import com.zzsz.utils.AliyunOSSConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @Classname InventoryServiceImpl
 * @Description
 * @Date 2025/9/2 8:19
 * @Created by SYL
 */

@Service
@Slf4j
public class InventoryServiceImpl implements InventoryService {
    @Autowired
     private InventoryMapper inventoryMapper;



    /**
     * 商品及其处在分类的库存列表
     * @return
     */
    @Override
    public List<ProductsCategoriesInventoryVO> list(ProductsCategoriesInventoryVO productsCategoriesInventoryVO) {
        List<ProductsCategoriesInventoryVO> list = inventoryMapper.list(productsCategoriesInventoryVO);
        // 为商品图片URL添加阿里云OSS前缀
        for (ProductsCategoriesInventoryVO item : list) {
            if (item.getProductImage() != null && !item.getProductImage().isEmpty() && !item.getProductImage().startsWith("http")) {
                item.setProductImage(AliyunOSSConstants.COMMON_URL + item.getProductImage());
            }
        }


        return list;
    }
    /**
     * 获取分类名称
     * @return
     */
    @Override
    public List<Tree<String>> getCategoryName() {


         List<ZzszProductCategories> list= inventoryMapper.selectCategory();
        // 创建树形节点配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        SimpleDateFormat dateFormatTool = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Tree<String>> treeNodes = TreeUtil.build(list, null, treeNodeConfig,  //// 1. 根节点父ID参数从"0"改为null，匹配数据库中根节点的parent_id=null
                (treeNode, tree) -> {
                    // 主键必须留着
                    tree.setId(treeNode.getCategoryId().toString());
                    // 2. 处理parent_id为null的情况，避免空指针异常
                    tree.setParentId(treeNode.getParentId() != null ? treeNode.getParentId().toString() : null);
                    // 其他字段,需要自定义设置
                    tree.setName(treeNode.getCategoryName());

                    // 扩展属性 ...
//                    tree.putExtra("description", treeNode.getDescription());
//                    tree.putExtra("createTime", treeNode.getCreatedAt() != null ? dateFormatTool.format(treeNode.getCreatedAt()) : null);
//                    tree.putExtra("updateTime", treeNode.getUpdatedAt() != null ? dateFormatTool.format(treeNode.getUpdatedAt()) : null);
                });



        return treeNodes;
    }

    @Override
    public List<ZzszProductCategories> getCategoryName1V() {
        return inventoryMapper.getCategoryName1V();
    }

    @Override
    public List<ZzszProductCategories> getCategoryName2V() {
        return inventoryMapper.getCategoryName2V();
    }

    @Override
    @ZzszRecordStockLog(desc = "添加商品",value = OperationType.FIRST_STOCK)
    public Long addProduct(ZzszAddProductsDTO zzszAddProductsDTO) {
//        zzszAddProductsDTO.getProductName();//商品名称
//        zzszAddProductsDTO.getSku();//商品SKU
//        zzszAddProductsDTO.getCategoryId1();//大分类ID
//        zzszAddProductsDTO.getCategoryId2();//小分类ID
//        zzszAddProductsDTO.getQuantity();//库存总数量
//        zzszAddProductsDTO.getCostPrice();//商品单价（成本价格）
//        zzszAddProductsDTO.getDescription();//商品描述
//        zzszAddProductsDTO.getStatus();//是否上架（1：上架，0：下架）
//        zzszAddProductsDTO.getPrice();//商品售价

        //对商品表进行添加
        int i = inventoryMapper.addProduct(zzszAddProductsDTO);
        // 插入后，自增ID会自动填充到对象对应的属性中
        System.out.println("生成的自增商品ID：" + zzszAddProductsDTO.getProductId());
        //对商品库存表进行添加
        int i1 = inventoryMapper.addProductInventory(zzszAddProductsDTO);
        //对商品预警表进行添加
        int i2 = inventoryMapper.addProductAlertsID(zzszAddProductsDTO);

        return (i>0&&i1>0&&i2>0&&i2>0)? zzszAddProductsDTO.getProductId():-1;
    }

    @Override
    public int addProductV2(ZzszAddProductsDTO zzszAddProductsDTO, MultipartFile productImage) {
        int i = inventoryMapper.addProduct(zzszAddProductsDTO);
        // 插入后，自增ID会自动填充到对象对应的属性中
        System.out.println("生成的自增商品ID：" + zzszAddProductsDTO.getProductId());
        //对商品库存表进行添加
        int i1 = inventoryMapper.addProductInventory(zzszAddProductsDTO);
        //对商品预警表进行添加
        int i2 = inventoryMapper.addProductAlertsID(zzszAddProductsDTO);



        return 0;
    }

    @Override
    public int addCategory1(ZzszProductCategories productCategories) {
        return inventoryMapper.addCategory1(productCategories);
    }

    @Override
    public int addCategory2(ZzszProductCategories productCategories) {
        return inventoryMapper.addCategory2(productCategories);
    }

    /**
     * 添加商品图片
     * @param productId
     * @param imageUrl
     * @return
     */
    @Override
    public int addProductImg(Long productId, String imageUrl) {
        int i = inventoryMapper.addProductImg(productId, imageUrl);
        log.info("添加商品图片，商品ID：{}，图片URL：{}", productId, imageUrl);
        return i;
    }

    /**
     * 添加库存
     * @param zzszAddProductsDTO
     * @return
     */
    @Override
    @ZzszRecordStockLog(desc = "添加库存",value = OperationType.IN_STOCK)
    public Long addInStock(ZzszAddProductsDTO zzszAddProductsDTO) {
        int i = inventoryMapper.addInStock(zzszAddProductsDTO);
        return i>0?zzszAddProductsDTO.getProductId() : -1L;

    }


}
